package com.zkca.xf.ui.activity.nfc;

import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.FaultJobLBean;
import com.zkca.xf.model.javabean.JobLBean;
import com.zkca.xf.model.javabean.uploadbean.RequestInspect;
import com.zkca.xf.presenter.JobLPresenter;
import com.zkca.xf.ui.activity.nfc.lochy.MainbActivity;
import com.zkca.xf.ui.activity.personprotect.Device_XActivity;
import com.zkca.xf.ui.activity.personprotect.DeviceaddAct;
import com.zkca.xf.ui.activity.personprotect.FaultJobSubmitActivity;
import com.zkca.xf.ui.activity.personprotect.FaultJob_LActivity;
import com.zkca.xf.ui.activity.personprotect.JobCheckActivity;
import com.zkca.xf.ui.activity.personprotect.Job_LActivity;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.JobLView;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

//手机
public class Activity_saomiao extends BaseTitleActivity implements JobLView {
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private String s;
    private Tag tag = null;
    private long id;
    private String shangye, id_old, pollingId, form, neirong, shebeiMingcheng;
    ImageView imageView;

    private String pollingId_;
    private boolean beidi;
    private String dijige, id2;
    private BluetoothAdapter bluetoothAdapter;

    private String deviseid;
    Intent intent2;
    private RequestInspect requestInspect;
    private JobLPresenter jobLPresenter;
    private int taskId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
//        }

        setContentView(R.layout.activity_saomiao);
        imageView = (ImageView) this.findViewById(R.id.imageView_phone);

        translateImpl(imageView);
        setTitleText("贴一贴");
        jobLPresenter = new JobLPresenter(this, this);
        intent2 = getIntent();
        shangye = intent2.getStringExtra("TAG");
//        if ("device".equals(shangye)) {
//            id_old = intent.getStringExtra("ID");
//            pollingId_ = intent.getStringExtra("pollingId");
//            beidi = intent.hasExtra("neirong");
//            if (beidi) {
//                neirong = intent.getStringExtra("neirong");
//                shebeiMingcheng = intent.getStringExtra("shebeiMingcheng");
//            }
//
//            String[] split = pollingId_.split("#");
//            pollingId = split[0];
//            form = split[1];
//
//        } else if ("xunjianJob".equals(shangye)) {
//            dijige = intent.getStringExtra("dijige");
//            Log.e("lishuai1234", dijige);
//        }
        setNFC();
    }

    private void toNextActivity() {
        Intent intent = new Intent();
        if ("deviceadd".equals(shangye)) {
            intent.setClass(Activity_saomiao.this, DeviceaddAct.class);
            intent.putExtra("ID", deviseid);
            startActivity(intent);
            finish();
        }
        if ("XUNJIAN".equals(shangye)) {
            JobLBean.DataBean data = (JobLBean.DataBean) intent2.getSerializableExtra("jobbean");
            LogUtil.e("扫描得到的：", deviseid + "上页带来的：" + data.getDevId());
            if (deviseid.equals(data.getDevId())) {
                intent.setClass(Activity_saomiao.this, JobCheckActivity.class);
                intent.putExtra("jobbean", data);
                startActivity(intent);
                finish();
            } else {
                ToastUtils.show(this, "该设备不是作业目标设备");
                intent.setClass(Activity_saomiao.this, Job_LActivity.class);
                intent.putExtra("taskId", data.getTaskId());
                startActivity(intent);
                finish();
            }
        }
        if ("F_XUNJIAN".equals(shangye)) {
             taskId = intent2.getIntExtra("taskId", -1);//deviseid
            initDvData(taskId,deviseid);
        }
        if ("WEIXIU".equals(shangye)) {
            FaultJobLBean.DataBean data = (FaultJobLBean.DataBean) intent2.getSerializableExtra("jobbean");
            LogUtil.e("扫描得到的：", deviseid + "上页带来的：" + data.getDevId());
            if (deviseid.equals(data.getDevId())) {
                intent.setClass(Activity_saomiao.this, FaultJobSubmitActivity.class);
                intent.putExtra("jobbean", data);
                startActivity(intent);
                finish();
            } else {
                ToastUtils.show(this, "该设备不是作业目标设备");
                intent.setClass(Activity_saomiao.this, FaultJob_LActivity.class);
                startActivity(intent);
                finish();
            }
        }

        if ("tietakankan".equals(shangye)) {
            intent.setClass(Activity_saomiao.this, Device_XActivity.class);
            intent.putExtra("deviceId", deviseid);
            startActivity(intent);
            finish();
        }
    }
//    private void init() {
//        text_Uid = (TextView) findViewById(R.id.mytext);
//    }

    public void translateImpl(View v) {
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int a = v.getWidth();
        int b = (width / 2) - (v.getWidth()) / 2;
        TranslateAnimation mTranslateAnimation = new TranslateAnimation(-width, -a, 0, 0);
        mTranslateAnimation.setInterpolator(new LinearInterpolator());
        mTranslateAnimation.setDuration(2000);
        mTranslateAnimation.setRepeatCount(Animation.INFINITE);
        mTranslateAnimation.setRepeatMode(Animation.REVERSE);
        v.setAnimation(mTranslateAnimation);
        mTranslateAnimation.start();

    }

    protected void setNFC() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Intent intent = new Intent();
        if (mNfcAdapter == null) {
            if (bluetoothAdapter != null) {
                if (bluetoothAdapter.isEnabled()) {
                    //跳转蓝牙连接界面
                    intent.setClass(Activity_saomiao.this, MainbActivity.class);

                    if ("deviceadd".equals(shangye)) {
                        intent.putExtra("TAG", "deviceadd");
                    }
                    if ("XUNJIAN".equals(shangye)) {
                        JobLBean.DataBean data = (JobLBean.DataBean) intent2.getSerializableExtra("jobbean");
                        intent.putExtra("jobbean", data);
                        intent.putExtra("TAG", "XUNJIAN");

                    }
                    if ("F_XUNJIAN".equals(shangye)) {
                        taskId = intent2.getIntExtra("taskId", -1);//deviseid
                        intent.putExtra("taskId", taskId);
                        intent.putExtra("TAG", "F_XUNJIAN");

                    }
                    if ("WEIXIU".equals(shangye)) {
                        FaultJobLBean.DataBean data = (FaultJobLBean.DataBean) intent2.getSerializableExtra("jobbean");
                        intent.putExtra("jobbean", data);
                        intent.putExtra("TAG", "WEIXIU");

                    }

                    if ("tietakankan".equals(shangye)) {

                        intent.putExtra("TAG", "tietakankan");

                    }


                    this.startActivity(intent);
                    finish();
                    return;
                } else {
                    // 请求打开 Bluetooth
                    intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, 3);
                    Toast.makeText(this, "请打开蓝牙的NFC功能", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }
            } else {
                Toast.makeText(this, "您的手机无法链接硬件！", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }


        }
        if (!mNfcAdapter.isEnabled()) {
            startActivity(new Intent("android.settings.NFC_SETTINGS"));
            Toast.makeText(this, "请打开手机的NFC功能", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[]{ndef};
        mTechLists = new String[][]{new String[]{NfcA.class.getName()}};

    }

    public void onResume() {
        super.onResume();
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent,
                    mFilters, mTechLists);
        Intent intent = getIntent();

        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
        } else if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            processTag(intent);
        } else if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processTag(intent);
    }

    //返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络  
    public static int GetNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = 3;
            } else {
                netType = 2;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    private void processTag(Intent intent) {

        tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag == null)
            return;

        System.out.println("tagIntent.getId()==" + tag.getId().toString());
        byte[] cardUid = tag.getId();
        s = this.ByteArrayToHexString(cardUid);
        id = Long.parseLong(s, 16);
        deviseid = id + "";

        Log.e("cardId==", deviseid + "///" + s);


        toNextActivity();
    }

    private String ByteArrayToHexString(byte[] inarray) { // converts byte arrays to string
        int i, j, in;
        String[] hex = {
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"
        };
        String out = "";

        for (j = 0; j < inarray.length; ++j) {
            in = inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }


    //验证作业是否存在

    private void initDvData( int taskId,String deviseid) {
        Map map = new HashMap<String, Object>();
        map.put("taskId", taskId);
        map.put("jobResult", 0 + "");
        map.put("devId", deviseid + "");
        requestInspect = new RequestInspect();
        requestInspect.setPageNum(1);
        requestInspect.setPageSize(1);
        requestInspect.setParam(map);
        requestInspect.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestInspect.setAction(4);
        requestInspect.setTimeStamp(TimeUtils.getTime());
        requestInspect.setSign(MyApplication.getInstance().generateDvSign(requestInspect));
        jobLPresenter.getJobL(requestInspect);
    }


    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void getJobL(JobLBean jobLBean) {
        if (jobLBean.getResult() == 0) {
            List<JobLBean.DataBean> data = jobLBean.getData();
            int size = data.size();
            Intent intent=new Intent();
            if (size!=0) {
                intent.setClass(Activity_saomiao.this, JobCheckActivity.class);
                intent.putExtra("jobbean", data.get(0));
                startActivity(intent);
                finish();
            } else {
                ToastUtils.show(this, "该设备不是作业目标设备");
                intent.setClass(Activity_saomiao.this, Job_LActivity.class);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
                finish();
            }
        }
    }
}
